package logic

import (
	"context"
	"encoding/json"
	"novel/models/cache"
	"novel/models/mysql"
	"time"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelListLogic {
	return &NovelListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NovelListLogic) NovelList(in *novelrpc.NovelListRequest) (*novelrpc.NovelListResponse, error) {
	// todo: add your logic here and delete this line
	var novels []mysql.Novel
	get := cache.Rdb.Get(l.ctx, "NovelList")
	if get.Val() == "" {
		mysql.DB.Debug().Limit(int(in.Size)).Find(&novels)
		marshal, _ := json.Marshal(novels)
		cache.Rdb.Set(l.ctx, "NovelList", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(get.Val()), &novels)
	}

	var NovelList []*novelrpc.NovelList
	for _, novel := range novels {
		list := novelrpc.NovelList{
			Title:   novel.Title,
			Profile: novel.Profile,
			Types:   novel.Types,
			UserId:  int64(novel.UserId),
			NovelId: int64(novel.ID),
		}
		NovelList = append(NovelList, &list)
	}
	return &novelrpc.NovelListResponse{
		List: NovelList,
	}, nil
}
